<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class category_db extends Model
{
	public $pk = 'category_id';
	public $table = 'ptx_category';

	var $linker = array(
			'tag' => array(
					'type' => 'hasmany',
					'map' => 'has_tags',
					'mapkey' => 'category_id',
					'ftable' => 'ptx_tag',
					'fkey' => 'category_id',
					'enabled' => false
			),
			'share' => 	array(
					'type' => 'hasmany',
					'map' => 'has_share',
					'mapkey' => 'category_id',
					'ftable' => 'ptx_share',
					'fkey' => 'category_id',
					'limit' => '4',
					'sort' => 'share_id DESC',
					'enabled' => false
			)
	);

	var $select_fields = " ptx_category.* ";

	public function search($page,$pagesize){
		$sort = " ptx_category.parent_id ASC ";
		return $this->pager($page, $pagesize)->findAllJoin('',$sort,' ptx_category.* ');
	}

	public function updateCache(){
		$this->updateRootCategroiesCache();
		$this->updateAllCategoryCache();
		$this->updateCategoryTreeCache();
		$this->updateLastLevelCategoryCache();
		$this->createCategoryTree();
		$this->createDeepCategoryTpl();
	}
	
	public function getSubCategories($catid){
		if($sbus = $this->findAll(array('parent_id'=>$catid),' display_order DESC ')){
			$subcats = array();
			foreach ($sbus as $skey=>$subcat){
				$sbus[$skey]['tags'] = $this->cleanTags($subcat['category_hot_words']);
			}
			return $sbus;
		}
		return false;
	}

	public function getRootCategroies(){
		$rs = pcache('r', 'root_category');
		if(!$rs){
			return $this->updateRootCategroiesCache();
		}
		return $rs;
	}

	public function updateRootCategroiesCache(){
		if($rs = $this->getRootCategroiesFromDb()){
			pcache('w', 'root_category',$rs);
			return $rs;
		}
		return FALSE;
	}
	
	public function getRootCategroiesFromDb(){
		return $this->findAll(array('parent_id'=>0,'is_open'=>1),' display_order DESC ');
	}

	public function getAllCategories(){
		$rs = pcache('r', 'all_category');
		if(!$rs){
			return $this->updateAllCategoryCache();
		}
		return $rs;
	}

	public function updateAllCategoryCache(){
		if($rs = $this->findAll('',' display_order DESC ')){
			$namecategories = array();
			$categories = array();
			foreach ($rs as $category){
				$enname = strtolower($category['category_name_en']);
				$namecategories[$enname] = $category;
				$categories[$category['category_id']] = $category;
			}
			pcache('w', 'all_category',$categories);
			pcache('w', 'name_category',$namecategories);
			return $rs;
		}
		return FALSE;
	}
	
	public function getNameCategories(){
		$rs = pcache('r', 'name_category');
		if(!$rs){
			return $this->updateAllCategoryCache();
		}
		return $rs;
	}

	public function getLastLevelCategories(){
		$rs = pcache('r', 'last_level_category');
		if(!$rs){
			return $this->updateLastLevelCategoryCache();
		}
		return $rs;
	}

	public function updateLastLevelCategoryCache(){
		$cats = $this->getAllCategories();
		$categories = array();
		foreach ($cats as $category){
			if(!$this->findCount(' parent_id='.$this->escape($category['category_id']).' ') && $category['is_open']){
				if($category['parent_id']>0){
					$category['category_name_cn']=$category['parent_name'].'-'.$category['category_name_cn'];
				}
				$categories[] = $category;
			}
		}
		pcache('w', 'last_level_category',$categories);
		return $categories;
	}

	public function getCategoryTree(){
		$cats = pcache('r', 'category_tree');
		if(!$cats){
			return $this->updateCategoryTreeCache();
		}
		return $cats;
	}
	public function getCleanCategoryTree(){
		$cats = pcache('r', 'category_tree_clean');
		if(!$cats){
			return $this->updateCategoryTreeCache();
		}
		return $cats;
	}
	
	public function getCategoryDeepTree(){
		$cats = pcache('r', 'category_deeptree');
		if(!$cats){
			return $this->createCategoryTree();
		}
		return $cats;
	}
	
	private function fillCategory($category){
		if($sbus = $this->findAll(array('parent_id'=>$category['category_id']),' display_order DESC ')){
			$subcats = array();
			foreach ($sbus as $skey=>$subcat){
				$sbus[$skey] = $this->fillCategory($subcat);
			}
			$category['subcats'] = $sbus;
		}
		$category['tags'] = $this->cleanTags($category['category_hot_words']);
		return $category;
	}
	
	public function createCategoryTree(){
		if($rs = $this->findAll(array('parent_id'=>0,'is_open'=>1),' display_order DESC ')){
			foreach ($rs as $key=>$category){
				$rs[$key] = $this->fillCategory($category);
			}
			pcache('w', 'category_deeptree',$rs);
			return $rs;
		}
		
		return false;
	}
	
	public function getCategoryDeepTreeTpl(){
		$tpl = pcache('r', 'category_deeptreetpl');
		if(!$tpl){
			return $this->createDeepCategoryTpl();
		}
		return $tpl;
	}
	
	public function createDeepCategoryTpl(){
		$categories = $this->getCategoryDeepTree();
		$tree .= '<div class="selectpopup popcategory"><ul class="popup-list">';
		foreach ($categories as $category){
			$tree = $this->fillCategoryDeepTreeTpl($category,$tree);
		}
		$tree .= '</ul></div>';
		pcache('w', 'category_deeptreetpl',$tree);
		return $tree;
	}
	
	private function fillCategoryDeepTreeTpl($category,$tpl=''){
		if($category['subcats']){
			$tpl .= '<li class="popup-item popup-item-parent"><a href="javascript:;" data-id="'.$category['category_id'].'">'.$category['category_name_cn'].'</a>';
			$tpl .= '<div class="selectpopup"><ul class="popup-list">';
			foreach ($category['subcats'] as $subcate){
				$tpl = $this->fillCategoryDeepTreeTpl($subcate,$tpl);
			}
			$tpl .= '</ul></div></li>';
		}else{
			$tpl .= '<li class="popup-item"><a href="javascript:;" data-id="'.$category['category_id'].'">'.$category['category_name_cn'].'</a></li>';
		}
		return $tpl;
	}

	public function updateCategoryTreeCache(){
		if($rs = $this->findAll(array('parent_id'=>0,'is_open'=>1),' display_order DESC ')){
			$cats = array();
			foreach ($rs as $key=>$category){
				$cats['cat'.$category['category_id']]['category_id'] = $category['category_id'];
				$cats['cat'.$category['category_id']]['category_name_cn'] = $category['category_name_cn'];
				$cats['cat'.$category['category_id']]['category_name_en'] = $category['category_name_en'];
				$cleanTags = $this->cleanTags($category['category_hot_words']);
				$cats['cat'.$category['category_id']]['tags'] = $cleanTags;
				$rs[$key]['tags'] = $cleanTags;
				if($sbus = $this->findAll(array('parent_id'=>$category['category_id'],'is_open'=>1),' display_order DESC ')){
					$subcats = array();
					foreach ($sbus as $skey=>$subcat){
						$subcats['cat'.$subcat['category_id']]['category_id'] = $subcat['category_id'];
						$subcats['cat'.$subcat['category_id']]['category_name_cn'] = $subcat['category_name_cn'];
						$subcats['cat'.$subcat['category_id']]['category_name_en'] = $subcat['category_name_en'];
						$subcats['cat'.$subcat['category_id']]['tags'] = $this->cleanTags($subcat['category_hot_words']);
						$scleanTags = $this->cleanTags($subcat['category_hot_words']);
						$subcats['cat'.$subcat['category_id']]['tags'] = $scleanTags;
						$sbus[$skey]['tags'] = $scleanTags;
					}
					$cats['cat'.$category['category_id']]['subcats'] = $subcats;
					$rs[$key]['subcats'] = $sbus;
				}
			}
			pcache('w', 'category_tree',$cats);
			pcache('w', 'category_tree_clean',$rs);
			return $cats;
		}
		return false;
	}

	private function cleanTags($hotwords){
		if($hotwords){
			$clean = array();
			$tags = explode(',', $hotwords);
			foreach ($tags as $tag){
				$clean[] = trim($tag);
			}
			return $clean;
		}
		return false;
	}

	public function find_one($conditions=NULL){
		$fields = $this->select_fields;
		return $this->findJoin($conditions,null,$fields);
	}

	public function delete_category($conditions){
		$category_id = $this->escape($conditions['category_id']);
		if($category_id){
			$this->delete($conditions);
			$this->update_category_top();
		}
	}


	public function get_category_top(){
		$results = pcache('r','category_top');
		if(!$results){
			$this->update_category_top();
			$results = pcache('r','category_top');
		}
		return $results;
	}

	public function find_category_byid($cid){
		$categories = $this->get_category_top();
		foreach ($categories as $category) {
			if($category['category_id']==$cid){
				return $category;
			}
		}
	}

	public function update_category_top(){
		$linker = $this->linker;
		$linker['share']['enabled'] = false;
		$linker['tag']['enabled'] = false;
		$linker['item']['condition'] = array('is_deleted'=>0);
		$this->linker = $linker;

		$results = $this->findAll('',' display_order DESC ');
		$api = load_api('share');
		foreach($results as $key => $cate){
			$home_shares = unserialize($cate['category_home_shares']);
			if(is_array($home_shares)){
				foreach ($home_shares as $share_key=>$share_value){
					if($share_key=='style'){ 
						$results[$key][$share_key] = $share_value;
					}else{
						$share = $api->getShareById($share_value);
						if($share)
							$results[$key][$share_key] = $api->prepareshare($share);
					}
				}
			}
		}

		pcache('w','category_top',$results);
	}

	function add_totalshare($cid){
		$category = $this->find_category_byid($cid);
		if($category['parent_id']){
			$this->add_totalshare($category['parent_id']);
		}
		return $this->incrField(array('category_id'=>$cid), 'total_share');
	}
	
	function remove_totalshare($cid){
		$category = $this->find_category_byid($cid);
		if($category['parent_id']){
			$this->remove_totalshare($category['parent_id']);
		}
		return $this->decrField(array('category_id'=>$cid), 'total_share');
	}
	
}
